package com.platform.file.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.platform.common.core.web.domain.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import static com.platform.file.utils.FileUploadUtils.containsJavaScript;

/**
 * @author twd
 * @date 2024/8/20 16:08
 */
@Component
@Slf4j
public class FileUploadInterceptor implements HandlerInterceptor {
    private PathMatcher pathMatcher = new AntPathMatcher();

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 定义白名单路径
        List<String> whiteList = Collections.singletonList(
                "/remote/uploadShareFile"
        );

        // 获取请求路径
        String requestUri = request.getRequestURI();

        // 判断是否在白名单中
        for (String pattern : whiteList) {
            if (pathMatcher.match(pattern, requestUri)) {
                return true; // 跳过检测
            }
        }
        // 检查请求是否包含文件
        if (request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
            for (MultipartFile file : fileMap.values()) {
                // 对每个文件进行XSS检测
                if (containsJavaScript(file)) {
                    AjaxResult result = AjaxResult.error("上传的文件中["+file.getOriginalFilename()+"]可能包含恶意脚本！");
                    returnJson(response, JSONObject.toJSONString(result));
                    return false; // 阻止请求继续进行
                }
            }
        }
        return true; // 允许请求继续
    }

    private void returnJson(HttpServletResponse response, String json) throws Exception{
        if (response == null){
            return;
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try (PrintWriter writer = response.getWriter()) {
            writer.print(json);
        } catch (IOException e) {
            log.error("response error", e);
        }
    }





}
